package cn.yunbamboos.rest.service.apidoc.meta;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.yunbamboos.rest.service.apidoc.IMeta;
import com.alibaba.fastjson2.JSONObject;

public class PathItem implements IMeta, Comparable<PathItem> {

    private final String url;

    private Operation post;

    private String apiId;

    public PathItem(String url) {
        this.url = url;
    }

    @Override
    public JSONObject toJSON() {
        JSONObject json = new JSONObject();
        if (ObjUtil.isNotNull(this.post)) {
            json.put("post", this.post.toJSON());
        }
        return json;
    }

    @Override
    public int compareTo(PathItem o) {
        if (StrUtil.isNotBlank(this.apiId) && StrUtil.isNotBlank(o.apiId)) {
            String[] ids1 = this.apiId.split("\\.");
            String[] ids2 = o.apiId.split("\\.");
            if (ids1.length == ids2.length) {
                int index = 0;
                int result = 0;
                while (index < ids1.length) {
                    String tmp1 = ids1[index];
                    String tmp2 = ids2[index];
                    result = tmp1.compareTo(tmp2);
                    if (result == 0) {
                        index++;
                    } else {
                        break;
                    }
                }
                return result;
            }
        }
        return 0;
    }

    public void setOperation(String type, Operation operation) {
        if ("post".equals(type)) {
            this.post = operation;
        }
    }

    public String getUrl() {
        return url;
    }

    public void setApiId(String apiId) {
        this.apiId = apiId;
    }


}
